<template>
  <div class="orders">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">订单管理</span>
      </div>
      <!-- 查询表单 -->
      <el-row>
        <el-col :span="24">
          <el-form inline class="query-form">
            <el-form-item label="订单编号">
              <el-input
                v-model="query.orderId"
                placeholder="请输入订单编号"
              ></el-input>
            </el-form-item>
            <el-form-item label="订单状态">
              <el-select
                v-model="query.orderStatus"
                placeholder="请选择订单状态"
              >
                <el-option label="已付款" value="已付款"></el-option>
                <el-option label="退单中" value="退单中"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
                <el-option label="已退单" value="已退单"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24">
          <el-button type="success" @click="handleAdd" class="add-button"
            >新增订单</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格展示 -->
      <el-row>
        <el-col :span="24">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            class="order-table"
          >
            <el-table-column
              prop="orderId"
              label="订单编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="createdAt"
              label="订单创建时间"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="orderStatus"
              label="订单状态"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="userId"
              label="订单负责人"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="storeId"
              label="商店编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="totalPrice"
              label="总金额"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleView(scope.row)"
                  >查看</el-button
                >
                <el-button type="text" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" @click="handleDelete(scope.row)"
                  >删除</el-button
                >
                <el-button type="text" @click="handleApplyRefund(scope.row)"
                  >申请退单</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="24">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
    >
      <el-form
        ref="orderForm"
        :model="orderForm"
        label-width="120px"
        class="edit-form"
      >
        <!-- 第一行 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号">
              <el-input
                v-model="orderForm.orderId"
                placeholder="请输入订单编号"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单创建时间">
              <el-date-picker
                v-model="orderForm.createdAt"
                type="datetime"
                placeholder="选择日期时间"
                :disabled="dialogTitle === '查看订单'"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单状态">
              <el-select
                v-model="orderForm.orderStatus"
                placeholder="请选择订单状态"
                :disabled="dialogTitle === '查看订单'"
                style="width: 100%"
              >
                <el-option label="已付款" value="已付款"></el-option>
                <el-option label="退单中" value="退单中"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
                <el-option label="已退单" value="已退单"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商店编号">
              <el-input
                v-model="orderForm.storeId"
                placeholder="请输入商店编号"
                :disabled="dialogTitle === '查看订单'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户编号">
              <el-input
                v-model="orderForm.userId"
                placeholder="请输入用户编号"
                :disabled="dialogTitle === '查看订单'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input
                v-model="orderForm.userName"
                placeholder="请输入用户名"
                :disabled="dialogTitle === '查看订单'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单时间">
              <el-date-picker
                v-model="orderForm.orderTime"
                type="datetime"
                placeholder="选择日期时间"
                :disabled="dialogTitle === '查看订单'"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额">
              <el-input
                v-model="orderForm.totalPrice"
                placeholder="请输入总金额"
                :disabled="dialogTitle === '查看订单'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="收件人地址">
              <el-input
                v-model="orderForm.address"
                placeholder="请输入收件人地址"
                :disabled="dialogTitle === '查看订单'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商店地址">
              <el-input
                v-model="orderForm.storeAddress"
                placeholder="请输入商店地址"
                :disabled="dialogTitle === '查看订单'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品列表 -->
        <el-form-item label="商品列表">
          <el-button
            type="success"
            @click="handleProductAdd"
            :disabled="dialogTitle === '查看订单'"
            style="float: left"
            >新增商品
          </el-button>

          <el-table
            :data="orderForm.orderProductDtos"
            border
            style="width: 100%"
            class="product-table"
          >
            <el-table-column
              prop="productId"
              label="商品编号"
              align="left"
            ></el-table-column>
            <el-table-column
              prop="productName"
              label="商品名称"
              align="left"
            ></el-table-column>
            <el-table-column label="商品图片" align="center">
              <template slot-scope="scope">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="scope.row.productImage"
                  fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderPrice"
              label="商品总价"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleProductEdit(scope.$index, scope.row)"
                  :disabled="dialogTitle === '查看订单'"
                  >编辑
                </el-button>
                <el-button
                  type="text"
                  @click="handleProductDelete(scope.$index)"
                  :disabled="dialogTitle === '查看订单'"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="saveOrder"
          v-if="dialogTitle !== '查看订单'"
          >保存</el-button
        >
      </span>
    </el-dialog>

    <!-- 商品信息 -->
    <el-dialog
      title="商品信息"
      :visible.sync="productDialogVisible"
      width="50%"
    >
      <el-form ref="productForm" :model="productForm" label-width="120px">
        <el-form-item label="商品编号">
          <el-select
            v-model="productForm.productId"
            placeholder="请选择商品编号"
            @change="loadProductDetails"
          >
            <el-option
              v-for="product in orderProductDtos"
              :key="product.productId"
              :label="product.productName"
              :value="product.productId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-input
            v-model="productForm.productImage"
            placeholder="请输入商品图片链接"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="productForm.productName"
            placeholder="请输入商品名称"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="商品数量">
          <el-input-number
            v-model="productForm.quantity"
            :min="1"
            @change="updateProductTotalPrice"
            placeholder="请输入商品数量"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品单价">
          <el-input-number
            v-model="productForm.price"
            :min="0.01"
            @change="updateProductTotalPrice"
            placeholder="请输入商品单价"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品总价">
          <el-input :value="productForm.orderPrice" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </span>
    </el-dialog>

    <!-- 申请退单对话框 -->
    <el-dialog
      title="申请退单"
      :visible.sync="refundDialogVisible"
      width="30%"
      :before-close="handleRefundClose"
    >
      <el-form ref="refundForm" :model="refundForm" label-width="120px">
        <el-form-item label="退单原因">
          <el-input
            type="textarea"
            v-model="refundForm.description"
            placeholder="请输入退单原因"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRefund">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  applyRefund, orderClose,
  orderCreat,
  orderEdit,
  ordersPageQuery,
} from "@/api/orderApi";
import { getAllProducts } from "@/api/productsApi";

export default {
  name: "AdminOrders",
  data() {
    return {
      query: {
        orderId: "",
        orderStatus: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "新增订单",
      orderForm: {
        orderId: "",
        productId: "",
        orderStatus: "",
        createdAt: "",
        updatedAt: "",
        storeId: "",
        userId: "",
        userName: "",
        orderTime: "",
        totalPrice: 0,
        address: "",
        storeAddress: "",
        orderProductDtos: [],
      },
      currentOrder: null,
      productDialogVisible: false,
      orderProductDtos: [], // 存储从后端获取的商品数据
      productForm: {
        productId: "",
        productImage: "",
        productName: "",
        quantity: 0,
        price: 0,
        orderPrice: 0,
      },
      currentProductIndex: -1,
      // 其他数据...
      refundDialogVisible: false, // 退单对话框的显示状态
      refundForm: {
        orderId: "", // 当前申请退单的订单编号
        description: "", // 退单原因
      },
    };
  },
  methods: {
    fetchData() {
      const params = {
        pageRequestDto: {
          page: this.currentPage,
          size: this.pageSize,
        },
        query: {
          orderId: this.query.orderId,
          orderStatus: this.query.orderStatus,
        },
      };
      ordersPageQuery(params)
        .then((res) => {
          this.tableData = res.data.records || [];
          this.total = res.data.total || 0;
        })
        .catch((error) => {
          console.error("获取订单数据失败：", error);
          this.$message.error("获取订单数据失败");
        });
    },
    resetQuery() {
      this.query.orderId = "";
      this.query.orderStatus = "";
      this.fetchData();
    },
    handleAdd() {
      this.dialogTitle = "新增订单";
      this.orderForm = {
        orderId: "",
        userId: "",
        productId: "",
        orderStatus: "",
        createdAt: "",
        updatedAt: "",
        storeId: "",
        ordererId: "",
        orderer: "",
        orderTime: "",
        totalPrice: 0,
        receiverAddress: "",
        storeAddress: "",
        orderProductDtos: [],
      };
      this.dialogVisible = true;
    },
    handleView(row) {
      this.dialogTitle = "查看订单";
      this.orderForm = {
        ...row,
        orderProductDtos: row.orderProductDtos || [],
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑订单";
      this.orderForm = {
        ...row,
        orderProductDtos: row.orderProductDtos || [],
      };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm(`确定要删除订单 ${row.orderId} 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          orderClose(row.orderId)
            .then(() => {
              this.$message.success("删除成功");
              this.fetchData();
            })
            .catch((error) => {
              console.error("删除订单失败：", error);
              this.$message.error("删除订单失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    saveOrder() {
      const order = { ...this.orderForm };
      if (this.dialogTitle === "新增订单") {
        orderCreat(order)
          .then(() => {
            this.$message.success("新增成功");
            this.fetchData();
          })
          .catch((error) => {
            console.error("新增订单失败：", error);
            this.$message.error("新增订单失败");
          });
      } else {
        orderEdit(order)
          .then(() => {
            this.$message.success("编辑成功");
            this.fetchData();
          })
          .catch((error) => {
            console.error("编辑订单失败：", error);
            this.$message.error("编辑订单失败");
          });
      }
      this.dialogVisible = false;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    handleProductAdd() {
      this.productForm = {
        productId: "",
        productImage: "",
        productName: "",
        quantity: 0,
        price: 0,
        orderPrice: 0,
      };
      this.currentProductIndex = -1;
      this.productDialogVisible = true;
    },
    handleProductEdit(index, row) {
      this.productForm = {
        ...row,
        orderPrice: row.orderPrice || 0,
      };
      this.currentProductIndex = index;
      this.productDialogVisible = true;
    },
    // 保存商品信息
    saveProduct() {
      if (this.currentProductIndex === -1) {
        // 新增商品
        this.orderForm.orderProductDtos.push({ ...this.productForm });
      } else {
        // 编辑商品
        this.$set(this.orderForm.orderProductDtos, this.currentProductIndex, {
          ...this.productForm,
        });
      }
      this.productDialogVisible = false; // 关闭商品信息对话框
      this.$message.success("商品信息保存成功");
    },
    handleProductDelete(index) {
      this.orderForm.orderProductDtos.splice(index, 1);
      this.$message.success("商品删除成功");
    },
    updateProductTotalPrice() {
      this.productForm.orderPrice =
        this.productForm.quantity * this.productForm.price;
    },
    // 获取商品数据
    fetchProducts() {
      getAllProducts()
        .then((res) => {
          this.orderProductDtos = res.data || [];
        })
        .catch((error) => {
          console.error("获取商品数据失败：", error);
          this.$message.error("获取商品数据失败");
        });
    },
    // 根据选择的商品编号加载商品详情
    loadProductDetails() {
      const selectedProduct = this.orderProductDtos.find(
        (product) => product.productId === this.productForm.productId
      );
      if (selectedProduct) {
        console.log("Selected Product:", selectedProduct);
        this.productForm.productImage = selectedProduct.productImage;
        this.productForm.productName = selectedProduct.productName;
        this.productForm.price = selectedProduct.price; // 假设后端返回了商品单价
        this.productForm.quantity = selectedProduct.quantity;
      }
    },
    handleApplyRefund(row) {
      this.refundForm.orderId = row.orderId; // 设置当前订单编号
      this.refundForm.description = ""; // 清空退单原因
      this.refundDialogVisible = true; // 显示退单对话框
    },
    submitRefund() {
      if (!this.refundForm.description) {
        this.$message.error("退单原因不能为空");
        return;
      }
      const putData = {
        description: this.refundForm.description, // 发送退单原因
      };
      // 调用后端接口申请退单
      applyRefund(this.refundForm.orderId, putData)
        .then(() => {
          this.$message.success("申请退单成功");
          this.refundDialogVisible = false; // 关闭退单对话框
          this.fetchData(); // 刷新订单列表
        })
        .catch((error) => {
          console.error("申请退单失败：", error);
          this.$message.error("申请退单失败");
        });
    },
    handleRefundClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.refundForm.description = ""; // 清空退单原因
          done();
        })
        .catch(() => {});
    },
  },
  mounted() {
    this.fetchData();
    this.fetchProducts(); // 在组件加载时获取商品数据
  },
};
</script>

<style scoped>
.orders {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.order-table {
  margin-top: 20px;
}

.add-button {
  float: left; /* 将按钮置于左侧 */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>